<script lang="ts" setup>
import type {
  BookAddRequest,
  BookQueryRequest,
  BookVO,
  PageBookVo,
} from '#/api/types';

import { onMounted, ref } from 'vue';

import { InputSearch } from 'ant-design-vue';

import { addBook, getBooksByLoginUser } from '#/api/core/books';
import BookDetail from '#/views/resources/books/book-detail.vue';
import BookList from '#/views/resources/books/book-list.vue';

// 定义响应式变量
const searchValue = ref<string>('');
const bookItems = ref<BookVO[]>([]);
const optionType = ref('add');
let resp: PageBookVo;

// 获取书籍信息
const onSearch = async (searchValue: string) => {
  const params: BookQueryRequest = {
    author: searchValue,
    current: 1,
    pageSize: 50,
    searchText: searchValue,
    sortField: 'book_id',
    title: searchValue,
  };

  resp = await getBooksByLoginUser(params);
  bookItems.value = resp?.records ?? []; // 更新响应式变量 bookItems
};

const currentBook: BookAddRequest = {
  author: '',
  description: '',
  genre: '',
  publicationYear: '',
  title: '',
};

// 是否添加书标志
const bookDetailFlag = ref(false);

const goToAddBook = () => {
  bookDetailFlag.value = true;
  optionType.value = 'add';
};

const handleSave = async (data: BookAddRequest) => {
  try {
    const bookId = await addBook(data); // 等待 Promise 解决
    if (bookId) {
      await onSearch(searchValue.value); // 确保在添加书籍后更新搜索结果
    }
  } catch (error) {
    console.error('保存书籍失败:', error);
  }
  bookDetailFlag.value = false;
};

const handleCancel = () => {
  bookDetailFlag.value = false;
  optionType.value = '';
};

onMounted(() => {
  onSearch(searchValue.value);
});
</script>

<template>
  <div id="book-main">
    <div class="operation-container">
      <button class="update-book-button" @click="goToAddBook">新增书籍</button>
      <InputSearch
        v-model:value="searchValue"
        enter-button="搜索"
        placeholder="输入书本信息，如书名、作者、书本描述等"
        style="width: 50%"
        @search="onSearch"
      />
      <BookDetail
        v-model:open="bookDetailFlag"
        :initial-data="currentBook"
        :option-type="optionType"
        @add="handleSave"
        @cancel="handleCancel"
      />
    </div>
    <BookList
      :items="bookItems"
      class="mt-5"
      title="相关书籍"
      @call-search="onSearch"
    />
  </div>
</template>
<style scoped>
.operation-container {
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 空间分配，将按钮推向右侧 */
  margin-top: 10px;
  margin-left: 20px;
  height: 50px;
}

.operation-container > * {
  margin-right: 10px; /* 添加右边距使两个元素之间有间隔 */
}

.update-book-button {
  padding: 8px 15px; /* 添加内边距 */
  background-color: #4caf50; /* 设置背景色 */
  color: white; /* 设置字体颜色 */
  border: none; /* 去掉边框 */
  border-radius: 5px; /* 圆角边框 */
  cursor: pointer; /* 鼠标悬停变成手指形状 */
  height: 70%;
}

.update-book-button:hover {
  background-color: #45a049; /* 鼠标悬停时改变背景色 */
}
</style>
